import pymysql
import datetime
import random
import time



def insertNovel(id,title,imgUrl,author,typeId,introduction):
    try:
        # 打开数据库连接
        db = pymysql.connect(host='139.196.196.131', port=3306, user='root', passwd='w1dewisd0m', db='hcloud-yunwei')
        db.ping(reconnect=True)
        cursor = db.cursor()
        # SQL 插入语句
        sql = "INSERT INTO b_novel(id,title,cover_url,author,type_id,read_type,introduction,create_date) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)"
        # 执行sql语句
        cursor.execute(sql,(id,title,imgUrl,author,typeId,1,introduction,datetime.datetime.now()))
        # 提交到数据库执行
        db.commit()
        db.close()
    except Exception as e:
        # 如果发生错误则回滚
        print(e)
        db.rollback()

def insertNovelItem(title,novelId,number,content):
    try:
        # 打开数据库连接
        db = pymysql.connect(host='139.196.196.131', port=3306, user='root', passwd='w1dewisd0m', db='hcloud-yunwei')
        db.ping(reconnect=True)
        cursor = db.cursor()
        t = time.time()
        id = ''.join(str(i) for i in random.sample(range(0, 9), 9)) + str(t)
        # SQL 插入语句
        sql = "INSERT INTO b_novel_item(id,title,novel_id,number,content,create_date) VALUES (%s,%s,%s,%s,%s,%s)"
        # 执行sql语句
        cursor.execute(sql, (id, title, novelId, number, content, datetime.datetime.now()))
        # 提交到数据库执行
        db.commit()
        db.close()
    except Exception as e:
        # 如果发生错误则回滚
        print(e)
        db.rollback()


def getMaxId(tableName):
    # 打开数据库连接
    db = pymysql.connect(host='139.196.196.131', port=3306, user='root', passwd='w1dewisd0m', db='hcloud-yunwei')
    db.ping(reconnect=True)
    cursor = db.cursor()
    # 获取id最大值
    maxId_sql = "select max(id) from b_novel"
    cursor.execute(maxId_sql)
    max_id = cursor.fetchall()
    if max_id[0][0] is None:
        id = 1
    else:
        id = max_id[0][0] + 1
    return id

def checkIsExist(novelName):
    db = pymysql.connect(host='139.196.196.131', port=3306, user='root', passwd='w1dewisd0m', db='hcloud-yunwei')
    db.ping(reconnect=True)
    cursor = db.cursor()
    count_sql = "select count(1) from b_novel where title = '%s'" % (novelName)
    cursor.execute(count_sql)
    count = cursor.fetchall()
    if count[0][0] >0:
        return True
    else:
        return False